package com.traitswu.websocket.embedtomcat;

import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.startup.Tomcat;

public class EmbedTomcatServer {

    public EmbedTomcatServer() {
    }

    public static void main(String[] args) throws Exception {
        String application = "test-websocket";
        int httpPort = 8081;
        if(args.length == 2) {
            httpPort = Integer.valueOf(args[1]).intValue();
        }

        int httpsPort = httpPort + 1;
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(httpPort);
        if(Boolean.getBoolean("https.enable")) {
            Connector httpsConnector = new Connector();
            httpsConnector.setScheme("https");
            httpsConnector.setSecure(true);
            httpsConnector.setPort(httpsPort);
            httpsConnector.setAttribute("keyAlias", "tomcat-embed");
            httpsConnector.setAttribute("keystorePass", "tomcat-embed");
            String keystoreFile = null;
            if(System.getProperty("keystore") != null) {
                keystoreFile = System.getProperty("keystore") + "/tomcat-embed.key";
            } else {
                if(System.getenv("NUKE_HOME") == null) {
                    throw new IllegalStateException("Keystore not found");
                }

                keystoreFile = System.getenv("NUKE_HOME") + "/tomcat-embed.key";
            }

            httpsConnector.setAttribute("keystoreFile", keystoreFile);
            httpsConnector.setAttribute("clientAuth", "false");
            httpsConnector.setAttribute("sslProtocol", "TLS");
            httpsConnector.setAttribute("SSLEnabled", Boolean.valueOf(true));
            tomcat.getService().addConnector(httpsConnector);
        }

        AprLifecycleListener aprLifecycleListener = new AprLifecycleListener();
        StandardServer server = (StandardServer)tomcat.getServer();
        server.addLifecycleListener(aprLifecycleListener);
//        tomcat.addWebapp("/" + application, (new File("webapp")).getAbsolutePath());
        tomcat.start();
        server.await();
    }
}